package com.example.course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.course.bean.Teacher;
import com.example.course.dto.TeacherDTO;
import com.example.course.dto.TeacherLoginDTO;
import com.example.course.dto.TeacherQueryDTO;
import com.example.course.mapper.TeacherMapper;
import com.example.course.service.TeacherService;
import com.example.course.tool.BCryptUtil;
import com.example.course.vo.TeacherVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Jasmine-drs
 * @description 针对表【teacher(教师表)】的数据库操作Service实现
 * @createDate 2025-04-22 15:36:40
 */
@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher>
		implements TeacherService {

	private final BCryptUtil bCryptUtil;

	public TeacherServiceImpl(BCryptUtil bCryptUtil) {
		this.bCryptUtil = bCryptUtil;
	}

	/**
	 * 登录逻辑实现
	 */
	@Override
	public TeacherVO login(TeacherLoginDTO loginDTO) {
		// 参数校验
		if (loginDTO == null || !StringUtils.hasText(loginDTO.getPhone()) || !StringUtils.hasText(loginDTO.getPassword())) {
			throw new IllegalArgumentException("手机号或密码不能为空");
		}

		// 根据手机号查询教师
		LambdaQueryWrapper<Teacher> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(Teacher::getPhone, loginDTO.getPhone());
		Teacher teacher = this.getOne(queryWrapper);

		// 判断教师是否存在
		if (teacher == null) {
			throw new IllegalArgumentException("教师不存在");
		}

		// 校验密码
		boolean encryptedPassword = bCryptUtil.checkPassword(loginDTO.getPassword(), teacher.getPassword());
		if (!encryptedPassword) {
			throw new IllegalArgumentException("密码错误");
		}

		// 转换为VO
		TeacherVO teacherVO = convertToVO(teacher);

		// 生成token（实际项目中应该使用JWT等方式）
		String token = generateToken(teacher);
		teacherVO.setToken(token);

		return teacherVO;
	}

	/**
	 * 注册逻辑实现
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public TeacherVO register(TeacherDTO teacherDTO) {
		// 参数校验
		if (teacherDTO == null || !StringUtils.hasText(teacherDTO.getName())
				|| !StringUtils.hasText(teacherDTO.getPhone())
				|| !StringUtils.hasText(teacherDTO.getPassword())) {
			throw new IllegalArgumentException("教师信息不完整");
		}

		// 检查手机号是否已注册
		LambdaQueryWrapper<Teacher> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(Teacher::getPhone, teacherDTO.getPhone());
		long count = this.count(queryWrapper);
		if (count > 0) {
			throw new IllegalArgumentException("该手机号已注册");
		}

		// 创建教师对象
		Teacher teacher = new Teacher();
		BeanUtils.copyProperties(teacherDTO, teacher);

		// 密码加密
		String encryptedPassword = DigestUtils.md5DigestAsHex(teacherDTO.getPassword().getBytes(StandardCharsets.UTF_8));
		teacher.setPassword(encryptedPassword);

		// 设置创建时间和更新时间
		LocalDateTime now = LocalDateTime.now();
		teacher.setCreateTime(now);
		teacher.setUpdateTime(now);

		// 保存到数据库
		this.save(teacher);

		// 转换为VO并返回
		return convertToVO(teacher);
	}

	/**
	 * 获取教师列表
	 */
	@Override
	public Page<TeacherVO> getTeacherList(TeacherQueryDTO queryDTO) {
		// 参数校验
		if (queryDTO == null) {
			queryDTO = new TeacherQueryDTO();
		}

		// 构建查询条件
		LambdaQueryWrapper<Teacher> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.like(StringUtils.hasText(queryDTO.getName()), Teacher::getName, queryDTO.getName())
				.like(StringUtils.hasText(queryDTO.getPhone()), Teacher::getPhone, queryDTO.getPhone())
				.orderByDesc(Teacher::getCreateTime);

		// 分页查询
		Page<Teacher> page = new Page<>(queryDTO.getCurrent(), queryDTO.getSize());
		Page<Teacher> teacherPage = this.page(page, queryWrapper);

		// 转换为VO
		Page<TeacherVO> voPage = new Page<>(teacherPage.getCurrent(), teacherPage.getSize(), teacherPage.getTotal());
		List<TeacherVO> voList = teacherPage.getRecords().stream()
				.map(this::convertToVO)
				.collect(Collectors.toList());
		voPage.setRecords(voList);

		return voPage;
	}

	/**
	 * 根据ID获取教师详情
	 */
	@Override
	public TeacherVO getTeacherById(Integer id) {
		// 参数校验
		if (id == null || id <= 0) {
			throw new IllegalArgumentException("教师ID不合法");
		}

		// 查询教师
		Teacher teacher = this.getById(id);
		if (teacher == null) {
			throw new IllegalArgumentException("教师不存在");
		}

		// 转换为VO并返回
		return convertToVO(teacher);
	}

	/**
	 * 将Teacher实体转换为TeacherVO
	 */
	private TeacherVO convertToVO(Teacher teacher) {
		if (teacher == null) {
			return null;
		}
		TeacherVO vo = new TeacherVO();
		BeanUtils.copyProperties(teacher, vo);
		return vo;
	}

	/**
	 * 生成token
	 * 注意：实际项目中应使用JWT等方式生成token
	 */
	private String generateToken(Teacher teacher) {
		// 简单示例，实际项目中应该使用JWT等方式
		return DigestUtils.md5DigestAsHex((teacher.getId() + "_" + teacher.getPhone() + "_" + System.currentTimeMillis())
				.getBytes(StandardCharsets.UTF_8));
	}
}




